package com.bybops.ui.activity

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.LinearLayoutManager
import android.view.KeyEvent
import android.view.View
import baseproject.com.mybaseproject.mvp.contract.MainContract
import baseproject.com.mybaseproject.mvp.presenter.MainPresenterImpl
import baseproject.com.mybaseproject.ui.base.BaseMvpActivity
import baseproject.com.mybaseproject.utils.ActivityUtils
import baseproject.com.mybaseproject.utils.scheduler.RxUtils
import com.bybops.R
import com.bybops.app.AppConstant
import com.bybops.app.MyApplication
import com.bybops.model.bean.EquipmentList
import com.bybops.ui.activity.account.LoginActivity
import com.bybops.utils.BlueToothUtils
import com.bybops.utils.TimeUtils
import com.bybops.widget.AlertDialog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.uuzuche.lib_zxing.activity.CodeUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_recycle_view.*
import kotlinx.android.synthetic.main.menu_header_layout.*
import kotlinx.android.synthetic.main.toolbar_base.*
import kotlinx.android.synthetic.main.toolbar_base.view.*


class MainActivity : BaseMvpActivity<MainContract.MainView, MainPresenterImpl>(), MainContract.MainView {


    override var mPresenter: MainPresenterImpl = MainPresenterImpl()
    private var mList = ArrayList<EquipmentList>()
    private var mAdapter: BaseQuickAdapter<EquipmentList, BaseViewHolder>? = null

    override fun getLayoutId(): Int? {
        return R.layout.activity_main
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //初始化View
        initView()
        //初始化列表
        initRecyclerView()
        //监听
        initLisenter()

        var intentFilter = IntentFilter()
        intentFilter.addAction(AppConstant.ACTION_STATUS_AUTH_FAIL)
        registerReceiver(mReceiver , intentFilter)

    }

    private val mReceiver = object : BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == AppConstant.ACTION_STATUS_AUTH_FAIL){
                //token失效
                AlertDialog(this@MainActivity).builder()
                        .setGone()
                        .setTitle("是否退出账号?")
                        .setNegativeButton("取消", R.color.color_2c9cf0, null)
                        .setPositiveButton("重新登录", R.color.color_2c9cf0) {
                            //跳转到登录界面
                            ActivityUtils.startActivityAndFinish(this@MainActivity , LoginActivity::class.java)
                        }
                        .show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(mReceiver)
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(R.id.mToolBar)
                .navigationBarColor(R.color.colorPrimaryDark)
                .init()
    }

    private fun initView() {
        //隐藏返回按钮
        mToolBar.mBtnBack.visibility = View.GONE
        mToolBar.title = resources.getString(R.string.menu_work_list)
        //隐藏中间标题
        mToolBar.mTitle.visibility = View.GONE
        val mToggle = ActionBarDrawerToggle(this, drawerLayout, mToolBar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close)
        mToggle.syncState()
        drawerLayout.addDrawerListener(mToggle)
        //姓名
        tvName.text = MyApplication.instance?.getUser()?.userName
        //手机号
        //用****替换手机号码中间4位
        val mobile = MyApplication.instance?.getUser()?.telephone
        val maskNumber = mobile?.substring(0, 3) + "****" + mobile?.substring(7, mobile.length)
        sbTel.text = maskNumber
        //搜索图标
//        mToolBar.mSubmit.setImageResource(R.mipmap.icon_search)
//        mToolBar.mSubmit.visibility = View.VISIBLE
    }

    private fun initRecyclerView() {
        var layoutManager = LinearLayoutManager(this)
        //设置为纵向排列
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        mRecyclerView.layoutManager = layoutManager
        //初始化数据适配器
        mAdapter = object : BaseQuickAdapter<EquipmentList, BaseViewHolder>(R.layout.item_work_list, mList) {
            override fun convert(helper: BaseViewHolder?, item: EquipmentList?) {
                //填充数据
                setItemData(helper, item)
            }
        }
        mAdapter?.emptyView = View.inflate(this, R.layout.empty_view_layout, null)
        //设置数据适配器
        mRecyclerView.adapter = mAdapter
        //刷新获取数据
        refreshLayout.autoRefresh(10)

    }

    /**
     * 设置数据
     */
    private fun setItemData(helper: BaseViewHolder?, item: EquipmentList?) {
        //设备条码
        helper?.setText(R.id.tv_operation_name, item?.barcode)
        //锁的状态
        when (item?.equipStatus) {
            // 使用中 是开着的
            EquipmentList.LockStatus.USERING -> helper?.setImageResource(R.id.imageLockStatus, R.mipmap.icon_unlock)
            else -> {
                //其他状态视为锁的状态
                helper?.setImageResource(R.id.imageLockStatus, R.mipmap.icon_locked)
            }
        }
        //电量文本
        helper?.setText(R.id.ltvLastEnergyText, BlueToothUtils.getEnergyText(item?.energy))
        //电量图标
        helper?.setImageResource(R.id.ltvLastEnergyIcon, BlueToothUtils.getEnergyResourceId(item?.energy))
        //医院
        helper?.setText(R.id.tvHospital, item?.hospital)
        //科室  病床
        helper?.setText(R.id.tvDeptAndBad, item?.department)
        //设备状态
        when (item?.equipStatus) {
            // 修的状态
            EquipmentList.LockStatus.ERROR -> {
                helper?.setImageResource(R.id.imLockStatus, R.mipmap.icon_lock_type_trim)
                //报修时间
                helper?.setText(R.id.tvTime, "报修时间 " + item?.pollTime?.let { TimeUtils.commLongToString(TimeUtils.dateFormat_3, it) })
            }
            else -> {
                //其他状态视为锁的状态
                helper?.setImageResource(R.id.imLockStatus, R.mipmap.icon_lock_type_check)
                //时间
                helper?.setText(R.id.tvTime, "截止时间 " + item?.pollTime?.let { TimeUtils.commLongToString(TimeUtils.dateFormat_3, it) })
            }
        }
    }

    /**
     * 初始化侧滑菜单选项监听
     */
    private fun initLisenter() {
        //点击事件
        mAdapter?.setOnItemClickListener { adapter, view, position ->
            var item = adapter.getItem(position) as EquipmentList
            mPresenter.equipmentGetDetail(item.equipSN)
        }
        //刷新监听
        refreshLayout.setOnRefreshListener {
            mPresenter?.appEquipmentGetList(true)

        }
        refreshLayout.setOnLoadmoreListener {
            mPresenter?.appEquipmentGetList(false)
        }

        //新设备启用
        RxUtils.rxClick(tvNewDeviceUse, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                ActivityUtils.startActivity(this@MainActivity, NewDeviceUseActivity::class.java)
            }
        })
        //设备列表
        RxUtils.rxClick(tvDeviceList, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {

            }
        })
        //日常巡检
        RxUtils.rxClick(tvDailyCheck, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
            }
        })
        //故障管理
        RxUtils.rxClick(tvBreakdownManager, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
            }
        })
        //联系客服
        RxUtils.rxClick(tvContactCustomerServer, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
            }
        })
        //设置
        RxUtils.rxClick(btnSetting, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                showToast(R.string.desc_developing)
            }
        })
        //退出
        RxUtils.rxClick(btnLogout, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                showLoginOutDialog()
            }
        })
        //扫一扫
        RxUtils.rxClick(imScan, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                //跳转到扫一扫界面
                val intent = Intent(this@MainActivity, ScanActivity::class.java)
                startActivityForResult(intent, 10)
//                BlueToothUtils.openLock("34:03:DE:44:5F:63")
            }
        })
    }

    /**
     * 显示登出对话框
     */
    private fun showLoginOutDialog() {
        AlertDialog(this).builder()
                .setGone()
                .setTitle("是否退出账号?")
                .setNegativeButton("取消", R.color.color_2c9cf0, null)
                .setPositiveButton("确定", R.color.color_2c9cf0) { mPresenter.loginOut() }
                .show()
    }

    override fun loginOutSucess(msg: String) {
        showToast(msg)
        //跳转到登录界面
        ActivityUtils.startActivityAndFinish(this@MainActivity, LoginActivity::class.java)

    }

    override fun loginOutFailed(errorMsg: String) {
        showToast(errorMsg)
    }

    /**
     * 获取工作列表成功
     */
    override fun appEquipmentGetListSucess(data: ArrayList<EquipmentList>) {
        mAdapter?.setNewData(data)
        refreshLayout.finishRefresh()
        refreshLayout.finishLoadmore()
    }

    override fun appEquipmentGetListFail(smg: String) {
        //获取列表失败
        refreshLayout.finishRefresh()
        refreshLayout.finishLoadmore()
        showToast(smg)
    }

    /**
     * 设备信息获取
     */
    override fun equipmentGetDetailSuccess(data: EquipmentList) {
        //根据类型不同跳转到不同的详情界面
        //检修详情界面
        var params = HashMap<String, Any?>()
        params["EquipmentList"] = data
        // 修的状态
        when (data?.equipStatus) {
            EquipmentList.LockStatus.ERROR -> {
                // 修的状态
                ActivityUtils.startActivityWithPramsForResult(this@MainActivity, CheckRepairDetailActivity::class.java, params, 20)
            }
            else -> {
                //巡检详情界面
                ActivityUtils.startActivityWithPramsForResult(this@MainActivity, PollCheckDetailActivity::class.java, params, 20)
            }
        }
    }

    /**
     * 退出应用
     */
    private var mkeyTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //返回按钮
            if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                drawerLayout.closeDrawer(GravityCompat.START)
            } else {
                if (System.currentTimeMillis() - mkeyTime > 2000) {
                    mkeyTime = System.currentTimeMillis()
                    showToast("再按一次退出")
                } else {
                    //关闭数据库
                    //关闭所有页面
                    ActivityUtils.removeAllActivitys()
                    //退出应用程序
                    System.exit(0)
                }
            }
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 20 && resultCode == Activity.RESULT_OK) {
            //刷新列表
            refreshLayout.autoRefresh(10)
        } else if (requestCode == 10) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                if (data.extras != null) {
                    if (data.extras.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        var result = data.extras.getString(CodeUtils.RESULT_STRING)
                        println("-----------result: $result")

                        //截取
                        if (result.startsWith("https://byb.yicai.wang/lockcode/")) {
                            var haha = result.substring("https://byb.yicai.wang/lockcode/".length, result.length)
                            showToast(haha)
                        }

                    } else {
                        showToast("解析二维码失败")
                    }
                } else {
                    return
                }
            }
        }
    }
}